import {SHA1} from "./SHA1";

const AppId = "A6053788184630";
const AppKey = "8B3F5860-2646-2C47-DC50-39106919B260";
var now = Date.now();
const secureAppKey = SHA1(AppId+"UZ"+AppKey+"UZ"+now)+"."+now;

/**
 * 方法请求头
 * @type {Headers}
 */
const headers = new Headers({
  "X-APICloud-AppId": AppId,
  "X-APICloud-AppKey": secureAppKey,
  "Accept": "application/json",
  "Content-Type": "application/json"
});

function get(url) {
  return fetch(url, {
    method: "GET",
    headers: headers,
  }).then(response => {
    return handleResponse(url, response);
  }).catch(err => {
    console.error(`Request failed. Url = ${url} . Message = ${err}`);
    // return {error: {message: "Request failed."}};
      return false;
  })
}
//解决json转换的循环调用问题
function print(obj){
        var seen = [];
        return JSON.stringify(obj, function(key, val) {
            if (typeof val == "object") {
                if (seen.indexOf(val) >= 0) return;
                seen.push(val)
            }
            return val;
        });
}
/*
对返回的数据进行处理：handelResponse(url,response)中，
第一个参数代表我们访问的url，rsponse表示从后台获取的结果，并且能够捕捉到异常。
 */
function post(url, data) {
  return fetch(url, {
    method: "POST",
    headers: headers,
    body: print(data)
  }).then(response => {
    return handleResponse(url, response);
  }).catch(err => {
    console.error(`Request failed. Url = ${url} . Message = ${err}`);
    // return {error: {message: "Request failed."}};
      return false;
  })
}

function put(url, data) {
  return fetch(url, {
    method: "PUT",
    headers: headers,
    body: print(data)
  }).then(response => {
    return handleResponse(url, response);
  }).catch(err => {
    console.error(`Request failed. Url = ${url} . Message = ${err}`);
    // return {error: {message: "Request failed."}};
      return false;
  })
}

/**
 * 对返回的数据进行处理：handelResponse(url,response)中，
 * 第一个参数代表我们访问的url，rsponse表示从后台获取的结果，并且能够捕捉到异常。
 * @param url
 * @param response
 * @returns {*}
 */
function handleResponse(url, response) {
  if(response.status < 500){
    return response.json();
  }else{
    console.error(`Request failed. Url = ${url} . Message = ${response.statusText}`);
    return {error: {message: "Request failed due to server error "}};
  }
}

export {get, post, put}